package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadApiService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.vo.user.LoginVo;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author NJG
 * @version 1.0
 * @date 2025/7/18 16:00
 * @description 文件上传
 */
@Service
@Slf4j
public class FileUploadApiServiceImpl implements FileUploadApiService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    /**
     * 文件上传
     * @param file
     * @return 图片地址
     */
    @Override
    public String fileUpload(MultipartFile file) throws IOException {
        //1.校验图片格式是否合法
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        if (bufferedImage == null){
            throw new GuiguException(500, "图片格式不合法");
        }

        //2.检验图片大小
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if (width > 2000 || height > 2000){
            throw new GuiguException(500, "图片大小不合法");
        }

        //3.将文件上传到Minio 规范：日期/文件唯一命名.后缀
        //3.1获取当前时期作为文件夹的名字
        String folderName = DateUtil.today();

        //3.2生成文件的唯一名称
        String extName = FileUtil.extName(file.getOriginalFilename());
        String fileName = "/" + folderName + "/" + UUID.randomUUID().toString() + "." + extName;

        // Upload unknown sized input stream.
        try {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
        } catch (Exception e) {
            log.error("上传失败 {"+ e.getMessage()+"}");
            throw new GuiguException(500,"上传失败");
        }

        return minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + fileName;
    }
}
